/**
 * 
 */
package com.gxa.ehome.service.impl;


import com.gxa.ehome.dao.UserDaoBase;
import com.gxa.ehome.dao.impl.UserDaoBaseImpl;
import com.gxa.ehome.entity.UserBase;
import com.gxa.ehome.exception.BusinessException;
import com.gxa.ehome.service.UserServiceBase;
import com.gxa.ehome.util.MD5Util;

import java.util.List;

/**
 * @author bilei
 * @date 2021年3月31日
 */
public class UserServiceBaseImpl implements UserServiceBase {

	// UserDao对象解决具体的持久化操作
	UserDaoBase userDaoBase = new UserDaoBaseImpl();


	@Override
	public UserBase register(UserBase user) throws Exception {
		//判断用户名是否存在
		UserBase selectUser = userDaoBase.selectByName(user.getName());
		if(selectUser == null) {
			// 不存在就继续注册
			user.setPwd(MD5Util.encode(user.getPwd()));
			Integer lines = userDaoBase.insert(user);
			if(lines>0) {
				selectUser= userDaoBase.selectByName(user.getName());
				return selectUser;
			}
		}else{
			throw new BusinessException("该用户名重复,请重新填写");
		}
		return null;

	}

	@Override
	public UserBase login(String name, String pwd) throws Exception {

		UserBase loUser = userDaoBase.selectByName(name);
/**System.out.println(9998);*/
		if (loUser != null) {
			if (MD5Util.encode(pwd).equals(loUser.getPwd())) {
				return loUser;
			} else {
				throw new BusinessException("用户名或密码不正确");
			}
		} else {
			throw new BusinessException("不存在的用户");
//			return null;

		}


	}

	@Override
	public List<UserBase> selectAlluser() throws Exception {
		List<UserBase> a1= userDaoBase.selectAll();

		return a1;
	}
	@Override
	public List<UserBase> selectAllByPage(Integer page, Integer size) throws Exception {
		List<UserBase> userList = userDaoBase.selectByPage(page, size);
		return userList;
	}

	@Override
	public Integer deleteById(Integer id) throws Exception {
		Integer integer = userDaoBase.deleteById(id);
		return integer;
	}

	@Override
	public void update(Integer id, UserBase user) throws Exception {
		UserBase selectedUser = userDaoBase.selectById(id);
		if(selectedUser != null){
			selectedUser.setName(user.getName());
			selectedUser.setPwd(MD5Util.encode(user.getPwd()));
		}
		userDaoBase.update(id,selectedUser);
	}

}
